<route lang="yaml">
  meta:
    title: 用户管理
  </route>

<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import { ElMessageBox } from 'element-plus'
import { ref } from 'vue'

const role = ref('')
const roles = [
  {
    value: 'Option1',
    label: 'Option1',
  },
  {
    value: 'Option2',
    label: 'Option2',
  },
  {
    value: 'Option3',
    label: 'Option3',
  },
  {
    value: 'Option4',
    label: 'Option4',
  },
  {
    value: 'Option5',
    label: 'Option5',
  },
]

// 编辑弹窗状态
const editDialogVisible = ref(false)
const formRef = ref<FormInstance>()
const formData = reactive<User>({
  userId: 0,
  userName: '',
  roleName: '',
  roleId: 0,
  phoneNumber: '',
  status: '启用',
})

// 新增弹窗状态
const addDialogVisible = ref(false)
const addFormRef = ref<FormInstance>()
const addFormData = reactive<Omit<User, 'userId'>>({
  userName: '',
  roleName: '',
  phoneNumber: '',
  status: '启用',
  roleId: 0,
})
interface User {
  userId: number
  userName: string
  roleName: string
  roleId: number
  phoneNumber: string
  status: string
}
const tableData: User[] = [
  {
    userId: 1,
    userName: 'admin',
    roleName: '超级管理员',
    roleId: 1,
    phoneNumber: '12345678901',
    status: '启用',
  },
  {
    userId: 2,
    userName: 'user1',
    roleName: '普通用户',
    roleId: 2,
    phoneNumber: '12345678902',
    status: '禁用',
  },
]

// 搜索关键字
const userName = ref('')

// 重置密码弹窗状态
function handleReset() {
  ElMessageBox.confirm(
    '确定要重置密码吗？',
    '重置确认',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      // 用户确认后执行重置逻辑
      console.warn('已重置密码')
    })
}
// 按钮点击处理
function handleAdd() {
  addFormRef.value?.resetFields()
  addDialogVisible.value = true
}

async function handleDelete(row: User) {
  await ElMessageBox.confirm(
    `确定要删除用户【${row.userName}】吗？`,
    '删除确认',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )

  // 用户确认后执行删除逻辑
  const index = tableData.findIndex(item => item.userId === row.userId)
  if (index > -1) {
    tableData.splice(index, 1)
    console.warn('已删除：', row)
    // 实际开发中此处应调用删除接口
  }
}
// 新增提交方法
function submitAddForm() {
  addFormRef.value?.validate(async (valid) => {
    if (valid) {
      // 生成模拟ID（实际应由后端生成）
      const newUserId = tableData.length ? Math.max(...tableData.map(u => u.userId)) + 1 : 1

      // 获取角色名称
      const selectedRole = roles.find(
        r => Number(r.value.replace('Option', '')) === addFormData.roleId,
      )

      tableData.push({
        ...addFormData,
        userId: newUserId,
        roleName: selectedRole?.label || '未知角色',
        roleId: addFormData.roleId, // 显式保留必要字段
      })

      console.warn('新增用户：', addFormData)
      addDialogVisible.value = false
    }
  })
}

// 表单验证规则
const rules = reactive({
  userName: [
    { required: true, message: '请输入用户名称', trigger: 'blur' },
  ],
  roleId: [
    { required: true, message: '请选择角色', trigger: 'change' },
  ],
  phoneNumber: [
    { required: true, message: '请输入联系方式', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' },
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' },
  ],
})

// 修改原有的handleEdit方法
function handleEdit(row: User) {
  Object.assign(formData, row)
  editDialogVisible.value = true
}

// 新增提交方法
function submitForm() {
  formRef.value?.validate((valid) => {
    if (valid) {
      // 这里调用实际保存接口
      console.warn('提交数据：', formData)
      editDialogVisible.value = false
      // 实际开发中此处应添加数据更新逻辑
    }
  })
}
</script>

<template>
  <div>
    <FaPageMain>
      <div class="mb-4 flex justify-between">
        <div class="button-group">
          <!-- 带图标+文字的按钮结构 -->
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            <span class="ml-1">新增</span>
          </el-button>
          <el-button type="primary" @click="handleReset">
            <el-icon><Edit /></el-icon>
            <span class="ml-1">重置密码</span>
          </el-button>
        </div>

        <div class="search-wrapper">
          <el-input
            v-model="userName"
            class="searchs"
            placeholder="请输入员工名称"
            clearable
            style="width: 200px;"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-select
            v-model="role"
            class="searchs"
            multiple
            placeholder="角色"
            style="width: 200px;"
          >
            <el-option
              v-for="item in roles"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table
          :data="tableData"
          row-key="roleId"
          style="width: 100%;"
          :fit="true"
          max-height="calc(100vh - 200px)"
        >
          <el-table-column type="selection" />
          <el-table-column property="userId" label="用户编号" />
          <el-table-column property="userName" label="用户名称" />
          <el-table-column property="roleName" label="角色名称" />
          <el-table-column property="phoneNumber" label="联系方式" />
          <el-table-column property="status" label="启用状态" />
          <el-table-column label="操作" width="auto">
            <template #default="{ row }">
              <div class="flex items-center">
                <el-button type="primary" link @click="handleEdit(row)">
                  <el-icon><Edit /></el-icon>
                  <span class="ml-1">编辑</span>
                </el-button>
                <el-button type="danger" link class="ml-3" @click="handleDelete(row)">
                  <el-icon><Delete /></el-icon>
                  <span class="ml-1">删除</span>
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination-wrapper" float-right>
        <el-pagination
          :page-size="20"
          :pager-count="11"
          layout="prev, pager, next"
          :total="1000"
        />
      </div>
    </FaPageMain>

    <!-- 修改对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="用户信息编辑"
      width="30%"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="用户编号" prop="userId">
          <el-input v-model="formData.userId" disabled />
        </el-form-item>
        <el-form-item label="用户名称" prop="userName">
          <el-input v-model="formData.userName" />
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select
            v-model="formData.roleId"
            placeholder="请选择角色"
            style="width: 100%;"
          >
            <el-option
              v-for="item in roles"
              :key="item.value"
              :label="item.label"
              :value="Number(item.value.replace('Option', ''))"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="联系方式" prop="phoneNumber">
          <el-input v-model="formData.phoneNumber" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="formData.status"
            placeholder="请选择状态"
            style="width: 100%;"
          >
            <el-option label="启用" value="启用" />
            <el-option label="禁用" value="禁用" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="submitForm">
          确认
        </el-button>
      </template>
    </el-dialog>
    <el-dialog
      v-model="addDialogVisible"
      title="用户信息新增"
      width="30%"
    >
      <el-form
        ref="addFormRef"
        :model="addFormData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="用户名称" prop="userName">
          <el-input v-model="addFormData.userName" />
        </el-form-item>
        <el-form-item label="角色" prop="roleName">
          <el-select
            v-model="addFormData.roleName"
            placeholder="请选择角色"
            style="width: 100%;"
          >
            <el-option
              v-for="item in roles"
              :key="item.value"
              :label="item.label"
              :value="Number(item.value.replace('Option', ''))"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="联系方式" prop="phoneNumber">
          <el-input v-model="addFormData.phoneNumber" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="addFormData.status"
            placeholder="请选择状态"
            style="width: 100%;"
          >
            <el-option label="启用" value="启用" />
            <el-option label="禁用" value="禁用" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="submitAddForm">
          确认
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

  <style scoped>
  .search-wrapper {
    display: flex;
    justify-content: flex-end;
  }

  .table-wrapper {
    width: 100%;
    margin-top: 16px;
    overflow-x: auto;
    border: 1px solid #ebeef5;
    border-radius: 4px;
  }

  .searchs {
    margin-right: 10px;
  }
  </style>
